package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
过滤器具体的处理逻辑如下：
        1、获取本次请求的URI
        2、判断本次请求是否需要处理,如果不需要处理，则直接放行
        3、判断登录状态，如果已登录，则直接放行
        4、如果未登录则返回未登录结果
*/


@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//    路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //String requestURL = request.getRequestURL().toString();
        //System.out.println(requestURL);

       // 1、获取本次请求的URI
        //System.out.println( request.getRequestURI());
        String requestURI = request.getRequestURI();
        String[] urls={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
      //  2、判断本次请求是否需要处理,如果不需要处理，则直接放行
        if(check(urls,requestURI)){
            filterChain.doFilter(request,response);
            log.info("登录和静态资源路线放行");
            return;

        }
       // 3.1、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("employee")!=null) {
            Long empId = (Long)request.getSession().getAttribute("employee");
//          要在放行前储存ID，放行后就不走下面的代码了
            BaseContext.setCurrentId(empId);

            log.info("已登录,用户ID为：{}",empId);

            filterChain.doFilter(request, response);
            return;
        }
        // 3.2、判断移动端登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user")!=null) {
            Long userId = (Long)request.getSession().getAttribute("user");
//          要在放行前储存ID，放行后就不走下面的代码了
            BaseContext.setCurrentId(userId);

            log.info("已登录,用户ID为：{}",userId);

            filterChain.doFilter(request, response);
            return;
        }

        //   4、如果未登录则返回未登录结果
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        log.info("未登录");
        return;
    }

    public boolean check(String[] urls,String requestURI){
        System.out.println(requestURI);
        for (String url : urls) {
            //System.out.println(url);
            boolean match = PATH_MATCHER.match(url,requestURI);
            if(match) {
                log.info("拦截到请求：{}",url);
                return true;
            }
        }
        return false;
    }
}
